package com.tudulist.web.utils;

import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.log4j.Logger;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.handler.RedirectRequestHandler;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.savedrequest.SavedRequest;

/**
 * Utilities class
 * 
 * @author seif
 * 
 */
public final class TudulistUtil {

	public static final String TODOLISTID = "todolistid";

	private static Logger logger = Logger.getLogger(TudulistUtil.class);

	/**
	 * formatting date time using pattern
	 * 
	 * @param date
	 * @return
	 */
	public static String doFormat(DateTime date) {
		DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
		return formatter.print(date);
	}

	/**
	 * Returns the URL the user accessed before he was redirected to the login
	 * page. This URL has been stored in the session by spring security.
	 * 
	 * @return the original URL the user accessed or null if no URL has been
	 *         stored in the session.
	 */
	public static String getOriginalUrl(HttpSession session) {
		SavedRequest savedRequest = (SavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
		if (savedRequest != null) {
			return savedRequest.getRedirectUrl();
		} else {
			return null;
		}
	}

	/**
	 * redirect to a url
	 * 
	 * @param url
	 */
	public static void redirectToUrl(String url) {
		RequestCycle.get().replaceAllRequestHandlers(new RedirectRequestHandler(url));
	}

	/**
	 * this method use the spring security's feature to logout a user
	 */
	public static void logout() {
		HttpServletRequest servletRequest = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
		redirectToUrl(servletRequest.getContextPath() + "/logout");
	}

	/**
	 * this methode return the current username from Security Context
	 * 
	 * @return
	 */
	public static String getCurrentUserUsername() {
		SecurityContext securityContext = SecurityContextHolder.getContext();
		org.springframework.security.core.userdetails.User springSecurityUser = (org.springframework.security.core.userdetails.User) securityContext
				.getAuthentication().getPrincipal();

		return springSecurityUser.getUsername();
	}

	/**
	 * returns a String under xml format
	 * @param data
	 * @return
	 */
	public static <T> String marshall(T data) {
		StringWriter dataConverted = new StringWriter();
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance("com.tudulist.model");
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.marshal(data, dataConverted);
		} catch (JAXBException e) {
			logger.error(e);
		}
		return dataConverted.toString();
	}
}
